# coding:utf-8
from django.db.models import Q
from rest_framework import viewsets
from MSB_ERP.utils.base_views import MultipleDestroyMixin, MultipleOpenMixin
from MSB_ERP.utils.pagination import GlobalPagination

from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from rest_framework import status
from rest_framework.decorators import action

from rest_framework import serializers
from goods_info.models import UnitsModel
from goods_info.serializer.units_serializer import UnitsSerializer


class UnitsView(viewsets.ModelViewSet, MultipleDestroyMixin, MultipleOpenMixin):
    """
    create:
    计量单位--新增

    计量单位新增, status: 201(成功), return: 新增计量单位信息

    destroy:
    计量单位--删除

    计量单位删除, status: 204(成功), return: None

    multiple_delete:
    计量单位--批量删除,必传参数：ids=[1,2,3,4...]

    计量单位批量删除, status: 204(成功), return: None

    multiple_open:
    计量单位--批量启用或者禁用,必传(json)参数：ids=[1,2,3,4...](列表中可以只有一个)，is_open=1/0

    {
        "ids":[1,2],
        "is_open":"0"
    }
    is_open=1表示禁用，is_open=0表示启用，
    计量单位批量启用或者禁用, status: 204(成功), return: None

    update:
    计量单位--修改,

    计量单位修改, status: 200(成功), return: 修改后的计量单位信息

    partial_update:
    计量单位--局部修改,可以传参任意属性的值，服务器会修改指定的属性值

    计量单位局部修改, status: 200(成功), return: 修改后的计量单位信息

    list:
    计量单位--获取分页列表，可选json参数:name(名称)

    {
        "name":"长沙",
    }
    计量单位列表信息, status: 200(成功), return: 计量单位信息列表

    retrieve:
    查询某一个计量单位

    查询指定ID的计量单位, status: 200(成功), return: 用户计量单位
    """

    queryset = UnitsModel.objects.all()
    serializer_class = UnitsSerializer
    #pagination_class = GlobalPagination
    def get_queryset(self):

        if self.action == 'find':  # 可能需要过滤查询,判断是否查询顶级类别还是某个子类别

            keyword = self.request.data.get('name', None)
            query = Q()
            if keyword:

                query.add(Q(basic_name__contains=keyword),'OR')
                query.add(Q(backup_name__contains=keyword),'OR')

            return UnitsModel.objects.filter(query).all()

        else:
            return UnitsModel.objects.all()

    json_params = openapi.Schema(type=openapi.TYPE_OBJECT, properties={
        'name': openapi.Schema(type=openapi.TYPE_STRING, description="计量单位的查询"),})

    @swagger_auto_schema(method='post', request_body=json_params,
        operation_description="仓库的过滤查询")
    @action(methods=['post'],detail=False)
    def find(self, request, *args, **kwargs):
        return super(UnitsView, self).list(request=request, *args, **kwargs)
